<?php
/*************************************************

Rsa加解密 - the
Author: Wanghuabin <17-8-10>

*************************************************/
class Rsa{
	  private static $PRIVATE_KEY;
    private static $PUBLIC_KEY;
	   /**
    * [__construct description]
    * @param string $pubKey  [公钥]
    * @param string $privKey [私钥]
    */
     function __construct($pubKey = '', $privKey = '') {
		
        self::$PUBLIC_KEY = $this->_readFile($pubKey);
        self::$PRIVATE_KEY = $this->_readFile($privKey);
		
    }
	
     public static function urlsafeB64Decode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }
	
    private function _error($msg){ 
      die('RSA Error:' . $msg); //TODO 
     }


	public static function urlsafeB64Encode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }
    private function _readFile($file){
     //   return $file;
      $ret = false;
      if (!file_exists($file)){
       $this->_error("The file {$file} is not exists");
      } else {
       $ret = file_get_contents($file);
      }
      return $ret;
     }	
	  /**
    *返回对应的私钥(内部类调用)
    */
    private static function getPrivateKey(){
     
        $privKey = self::$PRIVATE_KEY;
        // return $privKey;  
        return openssl_pkey_get_private($privKey); 

    }

    /**
    *返回对应的公钥(内部类调用)
    */
    private static function getPublicKey(){
        $pubKey = self::$PUBLIC_KEY;
        return openssl_pkey_get_public($pubKey);      
    }
 
    /**
     * 私钥加密
     */
    public static function privEncrypt($data)
    {   
        if(!is_string($data)){
            return null;
        }
        return openssl_private_encrypt($data,$encrypted,self::getPrivateKey())? self::urlsafeB64Encode($encrypted) : null;
    }
    
    /**
     * 私钥解密
     */
    public static function privDecrypt($encrypted)
    {
        if(!is_string($encrypted)){
            return null;
        }
        return (openssl_private_decrypt(self::urlsafeB64Decode($encrypted), $decrypted, self::getPrivateKey()))? $decrypted : null;
    }

    /**
     * 公钥加密
     */
    public static function pubEncrypt($data)
    {
        if(!is_string($data)){
            return null;
        }
        return openssl_public_encrypt($data,$encrypted,self::getPublicKey())? self::urlsafeB64Encode($encrypted) : null;
    }
    
    /**
     * 公钥解密
     */
    public static function pubDecrypt($encrypted)
    {
        if(!is_string($encrypted)){
            return null;
        }
        return (openssl_public_decrypt(self::urlsafeB64Decode($encrypted), $decrypted, self::getPublicKey()))? $decrypted : null;
    }
	 


}